package com.menxin.queueImpl;

/**
 * Created by Menx on 2019/3/6.
 */
@SuppressWarnings("ALL")
public class Array<E> {

    /**
     * 当前数组中元素数量,永远指向第一个未赋值索引
     */
    private int size;

    private E[] data = (E[]) new Object[0];

    public Array() {
        this(10);
    }

    public Array(int capacity) {
        if (capacity <= 0) {
            throw new IllegalArgumentException("容器容量需要大于0");
        }
        size = 0;
        data = (E[]) new Object[capacity];
    }

    public void insert(E e, int index) {
        if (index < 0) {
            throw new IllegalArgumentException("索引参数有误");
        }
        if (size >= data.length) {
            resize(data.length * 2);
        }
        for (int i = size; index < i; i--) {
            data[i] = data[i - 1];
        }
        data[index] = e;
        size++;
    }

    public void addFirst(E e) {
        insert(e, 0);
    }

    public void addLast(E e) {
        insert(e, size);
    }

    public boolean contains(E e) {
        for (E tmp : data) {
            if (tmp.equals(e)) {
                return true;
            }
        }
        return false;
    }

    public E remove(int index) {
        if (index < 0 || index > size) {
            throw new IllegalArgumentException("索引参数异常");
        }
        E tmp = data[index];
        for (int i = index ; i < size - 1; i++) {
            data[i] = data[i + 1];
        }
        //加快元素回收
        data[size - 1] = null;
        size--;
        if (size <= data.length / 4 && data.length / 2 > 0) {
            resize(data.length / 2);
        }
        return tmp;
    }

    public E removeFirst() {
        return remove(0);
    }

    public E removeLast() {
        return remove(size - 1);
    }

    public int find(E e) {
        for (int i = 0; i < size; i++) {
            if (data[i].equals(e)) {
                return i;
            }
        }
        return -1;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newData[i] = data[i];
        }

        data = newData;
    }

    public E get(int index){
        return data[index];
    }

    public E getFirst(){
        return data[0];
    }

    public E getLast(){
        return data[size - 1];
    }


    public int size(){
        return size;
    }

    public boolean isEmpty(){
        return size == 0;
    }

    public int capacity(){
        return data.length;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < size; i++) {
            buf.append(data[i].toString());
            if (i < size - 1) {
                buf.append(",");
            }
        }
        return buf.toString();
    }


}
